package org.spring.springboot.socket;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

@Component("MinaServerHandler")
public class MinaServerHandler extends IoHandlerAdapter {

	private Logger logger = LoggerFactory.getLogger(MinaServerHandler.class);

	public static Map<String, IoSession> sessions = new HashMap<>();

	public MinaServerHandler() {
	}

	@Override
	public void sessionCreated(IoSession session) throws Exception {
		logger.info("服务端与客户端创建连接...");
	}

	@Override
	public void sessionOpened(IoSession session) throws Exception {
		logger.info("服务端与客户端连接打开...");
	}

	@Override
	public void messageReceived(IoSession session, Object message) throws Exception {
		String msg = message.toString();
		DeviceMessage deviceMessage = new DeviceMessage(msg);
		if (StringUtils.isNotBlank(deviceMessage.getDeviceID())
				&& StringUtils.isNotBlank(deviceMessage.getDeviceType())) {
			sessions.put(deviceMessage.getDeviceType() + deviceMessage.getDeviceID(), session);
			session.setAttribute("device_type", deviceMessage.getDeviceType());
			session.setAttribute("device_id", deviceMessage.getDeviceID());
			
			/**
			 * 返回业务处理信息
			 **/
			ArrayList<String> args = new ArrayList<>();
			args.add("01");
			args.add("00");
			args.add("00000");
			args.add("004");
			args.add("OK");
			deviceMessage.setArgs(args);
			messageReceived(deviceMessage);
		}
		session.write(msg);
	}

	@Override
	public void messageSent(IoSession session, Object message) throws Exception {
		logger.info("服务端发送信息：{}-----成功",message);
	}

	@Override
	public void sessionClosed(IoSession session) throws Exception {
		logger.info("服务端与客户端连接关闭...");
		String device_type = (String) session.getAttribute("device_type");
		String device_id = (String) session.getAttribute("device_id");
		if (StringUtils.isNotBlank(device_type) && StringUtils.isNotBlank(device_id)) {
			sessions.remove(device_type + device_id);
		}
		session.close(true);
	}

	@Override
	public void sessionIdle(IoSession session, IdleStatus status) throws Exception {
		super.sessionIdle(session, status);
		logger.info("服务端进入空闲状态...");
	}

	@Override
	public void exceptionCaught(IoSession session, Throwable cause) throws Exception {
		cause.printStackTrace();
		logger.info("服务端发送异常..." + cause);
		session.close(true);
	}

	// 发送消息
	public void messageReceived(DeviceMessage deviceMessage) throws Exception {
		IoSession session = null;
		if (deviceMessage != null && StringUtils.isNotBlank(deviceMessage.getDeviceID())
				&& StringUtils.isNotBlank(deviceMessage.getDeviceType())) {
			session = sessions.get(deviceMessage.getDeviceType() + deviceMessage.getDeviceID());
		}
		if (session != null) {
			session.write(deviceMessage.toString());
		}
	}
}
